package com.emasdemo.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.emasdemo.R;
import com.emasdemo.application.SophixStubApplication;
import com.emasdemo.util.LogUtils;
import com.taobao.sophix.SophixManager;

import java.io.File;

public class SophixActivity extends AppCompatActivity {
    private TextView tv_status;
    private String mStatusStr = "";
    private Button btn_test;
    private LinearLayout ln_sophix;
    private boolean isImg = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sophix);

        initBar();
        tv_status = (TextView) findViewById(R.id.tv_sophix_status);
        btn_test = (Button) findViewById(R.id.btn_sophix_test);
        ln_sophix = (LinearLayout) findViewById(R.id.ln_sophix);

        findViewById(R.id.btn_sophix_download).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SophixManager.getInstance().queryAndLoadNewPatch();
            }
        });
        findViewById(R.id.btn_clean_patch).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SophixManager.getInstance().cleanPatches();
            }
        });
        btn_test.setText("补丁加载测试old");
        btn_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(SophixActivity.this, "无补丁状态", Toast.LENGTH_LONG).show();
            }
        });

        findViewById(R.id.btn_sophix_kill).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SophixManager.getInstance().killProcessSafely();
            }
        });

        findViewById(R.id.btn_sophix_provider).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkInstall();
            }
        });

        findViewById(R.id.btn_sophix_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isImg) {
                    isImg = false;
//                    ln_sophix.setBackgroundResource(R.mipmap.testvvv);
                } else {
                    isImg = true;
                    ln_sophix.setBackgroundColor(getResources().getColor(R.color.base_background));
                }
            }
        });

        updateConsole(SophixStubApplication.cacheMsg.toString());
        SophixStubApplication.msgDisplayListener = new SophixStubApplication.MsgDisplayListener() {
            @Override
            public void handle(final String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateConsole(msg);
                    }
                });
            }
        };

    }

    private void updateConsole(String content) {
        mStatusStr += content + "\n";
        if (tv_status != null) {
            tv_status.setText(mStatusStr);
        }
    }

    private void initBar() {
        findViewById(R.id.bar_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SophixActivity.this.finish();
            }
        });

        ((TextView) findViewById(R.id.bar_text)).setText("移动热修复");
    }

    private void checkInstall() {
        boolean haveInstallPermission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先获取是否有安装未知来源应用的权限
            haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {//没有权限
                AlertDialog alertDialog = new AlertDialog.Builder(this)
                        .setTitle("请开启未知来源权限")
                        .setMessage("应用需要打开安装未知来源应用权限，请去设置中开启权限")
                        .setCancelable(false)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Toast.makeText(SophixActivity.this, "您拒绝了权限，应用无法正常使用！", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        })
                        .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                            @RequiresApi(api = Build.VERSION_CODES.O)
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                toInStallPermissionSettingActivity();
                            }
                        }).create();
                alertDialog.show();
                return;
            }
        }
        //有权限，进行安装操作
        installAPK();
    }

    private void installAPK() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
        } else {
            intent.setAction(Intent.ACTION_VIEW);
        }

        File newFile = new File("/storage/emulated/0/sophix-provider.apk");
        if (newFile.exists()) {
            Log.i("provider", "文件存在");
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                /**Android 7.0以上的方式**/
                Log.i("provider", "进来了，说明是7.0以上设备");
                Uri contentUri = FileProvider.getUriForFile(SophixActivity.this, "com.emasdemo.fileprovider", newFile);
                SophixActivity.this.grantUriPermission("com.emasdemo", contentUri, intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            } else {
                intent.setDataAndType(Uri.fromFile(newFile), "application/vnd.android.package-archive");
            }
            SophixActivity.this.startActivity(intent);

        } else {
            Log.i("provider", "文件不存在");
            Toast.makeText(SophixActivity.this, "此功能为测试provider，如需使用，请放置/storage/emulated/0/sophix-provider.apk",
                    Toast.LENGTH_LONG).show();
        }
    }

    private final int REQUEST_CODE_INSTALL_PERMISSION = 999;

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void toInStallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, REQUEST_CODE_INSTALL_PERMISSION);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_INSTALL_PERMISSION) {
            checkInstall();//以防万一，再次检查权限
        }
    }

}
